package com.example.springsecuritydemo.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

/**
 * 自定义认证成功处理器
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal(); // 获取用户信息
        /*
        authentication.getCredentials();// 获取用户凭证信息： 密码 ,不推荐返回密码（不安全）
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();// 获取用户权限信息,
        */
        HashMap result = new HashMap();
        result.put("code",200);
        result.put("msg","登录成功");
        result.put("data",principal); //只将用户的身份信息返回到前端
        String json= JSON.toJSONString(result);

        //相应JSON结果，返回json数据给前端
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
